package com.yq.ylmall.product.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.ylmall.dto.product.BrandOperateDto;
import com.yq.ylmall.dto.product.BrandQueryDto;
import com.yq.ylmall.dto.product.RemoveDto;
import com.yq.ylmall.model.product.Brand;
import com.yq.ylmall.product.service.IBrandService;
import com.yq.ylmall.result.Result;
import com.yq.ylmall.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 分类品牌 后台前端控制器
 * </p>
 *
 * @author yzk789
 * @since 2024-05-31
 */
@Api(tags = "分类品牌管理接口")
@RestController
@RequestMapping("/admin/product/brand")
@RequiredArgsConstructor
public class BrandAdminController {
    private final IBrandService brandService;

    @ApiOperation(value = "分页条件查询分类品牌")
    @PostMapping("/page")
    public Result<IPage<Brand>> page(@RequestBody BrandQueryDto dto) {
        Page<Brand> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        brandService.page(
                page,
                Wrappers.<Brand>lambdaQuery()
                        .like(StringUtils.hasText(dto.getName()), Brand::getName, dto.getName())
                        .orderByDesc(Brand::getCreateTime)
        );
        return Result.ok(page);
    }

    @ApiOperation(value = "查询全部品牌")
    @GetMapping("/findAll")
    public Result findAll(){
        return Result.ok(brandService.list());
    }

    @ApiOperation(value = "分类品牌操作：有ID更新，无ID新增")
    @PostMapping("/operate")
    public Result<Object> addOrUpdateUnit(@RequestBody BrandOperateDto dto) {
        boolean success;
        if (dto.getId() != null) {
            success = brandService.doUpdate(dto);
        } else {
            success = brandService.save(BeanUtil.copyProperties(dto, Brand.class));
        }
        return success ? Result.ok(ResultCode.SAVE_SUCCESS) : Result.fail(ResultCode.SAVE_FAIL);
    }

    @ApiOperation(value = "删除分类品牌")
    @DeleteMapping("/remove")
    public Result<Object> delBrandById(@RequestBody RemoveDto dto) {
        boolean success = brandService.doRemoveById(dto);
        return success ? Result.ok(ResultCode.DELETE_SUCCESS) : Result.fail(ResultCode.DELETE_FAIL);
    }

    @ApiOperation(value = "批量删除分类品牌")
    @DeleteMapping("/remove/batch")
    public Result<Object> delBrandByIds(List<Long> ids) {
        boolean success = brandService.doRemoveByIds(ids);
        return success ? Result.ok(ResultCode.DELETE_SUCCESS) : Result.fail(ResultCode.DELETE_FAIL);
    }
}
